import pymysql
from pprint import pprint
from public_article_test import public_article
from public_search_test import public_search_api
from openpyxl import Workbook


def add_info_article(public_article_list, public_info):
    public_article_info_list = list()
    for public_article in public_article_list:
        item = dict()
        item["article"] = public_article
        item['gzh'] = public_info
        public_article_info_list.append(item)
    return public_article_info_list


def save_info_to_excel(article_info, author_info):
    wb = Workbook()
    file_name = author_info['public_name'] + "的文章.xlsx"
    ws = wb.active
    for index in range(len(article_info)):
        ws.append([article_info[index]['article']['title'],
                   article_info[index]['article']['url'],
                   article_info[index]['article']['abstract'],
                   article_info[index]['article']['publish_date'],
                   article_info[index]['gzh']['public_name'],
                   article_info[index]['gzh']['public_qrcode'],
                   article_info[index]['gzh']['authentication'],
                   article_info[index]['gzh']['introduction']])
    wb.save(filename=file_name)


def save_info_to_mysql(article_info):
    db = pymysql.connect("localhost", "root", "root", "python_final")
    cursor = db.cursor()
    sql = "insert into officialaccount values(null,%s,%s,%s,%s,%s,%s,%s)"
    for index in range(len(article_info)):
        val = (article_info[index]['article']['title'],
               article_info[index]['article']['url'],
               article_info[index]['article']['abstract'],
               article_info[index]['article']['publish_date'],
               article_info[index]['gzh']['public_name'],
               article_info[index]['gzh']['authentication'],
               article_info[index]['gzh']['introduction'])
        cursor.execute(sql, val)
    db.commit()
    db.close()


def process_console():
    public_name = input("请输入要查找的公众号：")
    public_info = public_search_api(public_name)
    print("公众号信息：")
    pprint(public_info)
    num = input("是否查询该作者的文章：1>是 2>否：")
    if num == "1":
        public_article_list = public_article(public_info['public_name'])
        public_article_list = add_info_article(public_article_list, public_info)
        # save_info_to_excel(public_article_list, public_info)
        save_info_to_mysql(public_article_list)
        print("保存成功!")
    else:
        print("欢迎再次使用")


if __name__ == '__main__':
    process_console()
